package ch.abcm.remsmobile.REMSMobile.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import ch.abcm.remsmobile.REMSMobile.network.networkutils.NetworkManager;
import ch.abcm.remsmobile.REMSMobile.network.networkutils.SSIDScanner;

public class NetworkController extends BroadcastReceiver {

    public static final String TAG = "NetworkController";

    public static final String REMS_SSID = "REMS_Network";
    public static final String REMS_WIFI_PASSWORD = "qwertzuiop";
    public static final String UPDATE_STATUS_ACTION = "ch.bfh.abcm.rems.NetworkController.UPDATE_STATUS";
    public static final long UPDATE_STATUS_WAITTIME = 1000 * 10; // 10 Sekunden

    private boolean deviceConnected;
    private boolean REMSNetworkAvailable;

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.d(TAG, "Update Status");

        SSIDScanner scanner = new SSIDScanner(context);
        NetworkManager networkManager = new NetworkManager(context);

        boolean accesspointIsActive = scanner.isAccesspointActive();
        Log.d(TAG, "Accesspoint is Active:" + accesspointIsActive);
        if (!accesspointIsActive) {
            scanner.enableWiFi();
            this.deviceConnected = scanner.isDeviceConnectedToSSID(REMS_SSID);
            Log.i(TAG, "Device Connected to a Network with SSI " + REMS_SSID + ": " + deviceConnected);
            if (!deviceConnected) {
                REMSNetworkAvailable = scanner.isWifiWithSSIDAvailable(REMS_SSID);
                Log.i(TAG, "Network with SSID " + REMS_SSID + " is available: " + REMSNetworkAvailable);
                if (REMSNetworkAvailable) {
                    networkManager.connectToNetwork(REMS_SSID, REMS_WIFI_PASSWORD);
                } else {
                    networkManager.createWiFiNetwork();
                }
            }
        }

        Handler handler = new Handler();
        Log.d(TAG, "StartPostDelayedHandler with delay: " + (UPDATE_STATUS_WAITTIME / 1000) + " sec");
        handler.postDelayed(new RepeatUpdate(context), UPDATE_STATUS_WAITTIME);

    }

    private class RepeatUpdate implements Runnable {

        private Context context;

        private RepeatUpdate(Context context) {
            this.context = context;
        }

        public void run() {
            Intent intent = new Intent(UPDATE_STATUS_ACTION);
            Log.d(TAG, "Send UpdateIntent: " + UPDATE_STATUS_ACTION);
            context.sendBroadcast(intent);
        }

    }
    
    public static Intent getStartIntent() {
        return new Intent(UPDATE_STATUS_ACTION);
    }
}
